package view;
import javax.imageio.ImageIO;
import javax.swing.*;

import controller.ImageHandling;
import net.miginfocom.swing.MigLayout;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;

public class Entry extends JFrame {
	
	private static final long serialVersionUID = 1L;

	public Entry() throws IOException		{
		JButton Exit=new JButton("Exit");
		
		try {
			  File imageCheck = new File("resources/exit.png");
			   Image img = ImageIO.read(imageCheck);
			   Exit.setIcon(new ImageIcon(img));
			  
			 } 
		catch (IOException ex) {
		}
		
		
		final JLabel test=new JLabel("Error,proceed again");
			test.setForeground(Color.red);
		JButton Connect=new JButton("Connect");
		JLabel userLabel=new JLabel("Username: ");
		JLabel passLabel=new JLabel("Password: ");
		final JTextField userField=new JTextField(15);	
		final JPasswordField passField=new JPasswordField(15);
		final JFrame frame = new JFrame("Enter Service");
		frame.pack();
		JPanel p=ImageHandling.AssignBg("resources/blackbg.jpg");
		p.setLayout(new MigLayout("","25[]15[]","30[]10[]10[][]"));
		frame.setContentPane(p);//end set content pane
	    frame.setLocationRelativeTo(null);
	    frame.setVisible(true);
	    frame.setSize(340,200);
	    frame.setResizable(false);
	    JRootPane rootPane = frame.getRootPane();
	    rootPane.setDefaultButton(Connect);
	    frame.add(userLabel);
	    frame.add(userField,"wrap");
	    
	    frame.add(passLabel);
	    frame.add(passField,"wrap");
	    frame.add(test,"wrap,span 2, align center");
	    test.setVisible(false);
	    frame.add(Connect,"align center, span, wrap");
	    frame.add(Exit,"align right, span, wrap");
	    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    
	  //action listener exit
		ActionListener actionListenerExit=new ActionListener()	{
			public void actionPerformed(ActionEvent actionEvent)	{
				System.exit(1);
			}

			
			
		};
		
		Exit.setMnemonic(KeyEvent.VK_ESCAPE);
		Exit.registerKeyboardAction
		(actionListenerExit, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), 
				JComponent.WHEN_IN_FOCUSED_WINDOW);
		
		//action listener exit
				ActionListener actionListenerConnect=new ActionListener()	{
					public void actionPerformed(ActionEvent actionEvent)	{
						try {
							boolean result=controller.Connect.enter(userField.getText(),passField.getPassword());
							if(result==true)	{
								new MainMenu(userField.getText());
								frame.setVisible(false);
							}
							else	{
								test.setVisible(true);
							}
						} 
						catch (IOException e) {
							e.printStackTrace();
						}
					}

					
					
				};
		
		Exit.addActionListener(actionListenerExit);
		Connect.addActionListener(actionListenerConnect);
	}
	
	
}
